#include "ds18b20.h"

static struct mgos_onewire *ow;
static float temp = 0.0;

void init_ds18b20(void)
{
    ow = mgos_onewire_create(DATA_DS18B20);
    if (ow == NULL)
    {
        printf("one wire init failed.\n");
    }
    else
    {
        printf("one wire init successful.\n");
    }
}

float get_ds18b20(void)
{
    return temp;
}

// 转换到浮点
static float toFloat(uint16_t data)
{
    if (data & 0x8000)
        return -1 * ((uint16_t)(~data + 1) / 256.0f);
    else
        return (data / 256.0f);
}

//cb
static void cb_read(void *arg)
{
    if (!mgos_onewire_reset(ow))
    {
        printf("reset for read failed\n");
        return;
    }

    mgos_onewire_skip(ow);
    mgos_onewire_write(ow, 0xbe);
    //read
    uint8_t data[BYTE_READ];
    mgos_onewire_read_bytes(ow, data, BYTE_READ);
    uint16_t *p_data = (uint16_t *)(data);
    *p_data &= ~1;
    *p_data <<= 4;
    temp = toFloat(*p_data);
    printf("d0:%d,d1:%d,ds18b20 temp is:%3.1f\n", data[0], data[1], temp);

    mgos_onewire_reset(ow);

    (void)arg;
}

void read_ds18b20(void)
{
    if (mgos_onewire_reset(ow))
    {
        mgos_onewire_skip(ow);
        mgos_onewire_write(ow, 0x44);
        //wait
        mgos_set_timer(760, false, cb_read, NULL);
    }
    else
    {
        printf("No ds18b20!\n");
    }
}